<template>
  <ContentWrap :bodyStyle="{ padding: '0px' }" class="border-none! bg-transparent! mb-0!">
    <ContentWrap v-loading="formLoading" :title="'员工信息'">
      <el-tabs v-model="activeName1" type="border-card" class="mb-10px">
        <el-tab-pane label="基础信息" name="basicsInfo">
          <UserForm ref="basicsRef" v-model:activeName="activeName1" :propFormData="formData" />
        </el-tab-pane>
        <el-tab-pane label="户籍信息" name="resident">
          <ResidentForm
            ref="residentRef"
            v-model:activeName="activeName1"
            :propFormData="formData"
          />
        </el-tab-pane>
        <el-tab-pane label="紧急联系人" name="emergency">
          <EmerencyForm
            ref="emergencyRef"
            v-model:activeName="activeName1"
            :propFormData="formData"
          />
        </el-tab-pane>
        <el-tab-pane label="教育经历" name="education">
          <EducationForm
            ref="educationRef"
            v-model:activeName="activeName1"
            :propFormData="formData"
          />
        </el-tab-pane>
        <el-tab-pane label="家庭成员" name="family">
          <FamilyForm ref="familyRef" v-model:activeName="activeName1" :propFormData="formData" />
        </el-tab-pane>
        <el-tab-pane label="工作经历" name="workExperience">
          <WorkExperienceForm
            ref="workExperienceRef"
            v-model:activeName="activeName1"
            :propFormData="formData"
          />
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="岗位信息" name="post">
          <PostForm
            ref="postRef"
            v-model:activeName="activeName"
            :propFormData="formData"
            @update-status="updateStatus"
          />
        </el-tab-pane>
      </el-tabs>
      <el-form class="mt-20px">
        <el-form-item>
          <div class="flex justify-center w-full">
            <el-button :loading="formLoading" type="primary" @click="submitForm"> 保存 </el-button>
            <el-button @click="close">返回</el-button>
          </div>
        </el-form-item>
      </el-form>
    </ContentWrap>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep, update } from 'lodash-es'
import * as UserApi from '@/api/system/user'
import UserForm from './UserForm.vue' //基础信息
import PostForm from './PostForm.vue' //岗位信息
import ResidentForm from './ResidentForm.vue' //户籍信息
import EmerencyForm from './EmerencyForm.vue' //紧急联系人
import EducationForm from './EducationForm.vue' //教育经历
import FamilyForm from './FamilyForm.vue' //家庭信息
import WorkExperienceForm from './WorkExperienceForm.vue' //工作经历
import { useTagsViewStore } from '@/store/modules/tagsView'
import { isEmpty } from '@/utils/is'

defineOptions({ name: 'TenantAdd' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const activeName = ref('post') // Tag 激活的窗口
const activeName1 = ref('basicsInfo') // Tag 激活的窗口

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const basicsRef = ref() // 基础信息 Ref
const postRef = ref() //岗位信息 Ref
const residentRef = ref() //户籍信息 Ref
const emergencyRef = ref() //紧急联系人信息 Ref
const educationRef = ref() //教育经历 ref
const familyRef = ref() //家庭成员
const workExperienceRef = ref() //工作经历ref
const { push, currentRoute } = useRouter() // 路由
const { params } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const formData = ref<UserApi.UserVO>({
  avatar: '',
  bareheaded: '',
  nickname: '',
  familyName: '',
  jobNumber: '',
  postType: [],
  deptId: '',
  mobile: '',
  education: '',
  marital: '',
  email: '',
  idNum: '',
  id: undefined,
  userAge: '',
  username: '',
  password: '',
  sex: 2,
  userBirthday: undefined,
  userNationalities: '1',
  userPolitical: undefined,
  userSource: undefined,
  userStatus: undefined,
  status: undefined,
  postIds: [],
  entryDate: '', //入职日期
  officialDate: '', //转正日期
  dimissionDate: '', //离职日期
  // 户籍信息
  houseCity: '', //户口所在地
  houseAddress: '', //户口所在地地址
  liveCity: '', //现居地
  liveAddress: '', //现居地地址
  // 紧急联系人
  usersLinkmanSaveReqVOList: [
    {
      username: '',
      mobile: '',
      relation: ''
    }
  ], //紧急联系人
  // 家庭成员
  usersFamilySaveReqVOList: [
    {
      familyName: '',
      familySex: '',
      familyRelation: '',
      familyIdNumber: '',
      workOrganization: '',
      workPost: '',
      address: ''
    }
  ],
  // 教育经历
  usersEducationSaveReqVOList: [
    {
      schoolName: '',
      schoolAddress: '',
      education: '',
      isFullTime: false,
      profession: '',
      entranceDate: undefined,
      graduateDate: undefined,
      certificate: ''
    }
  ],
  // 工作经历
  usersExperienceSaveReqVOList: [
    {
      companyName: '', //单位名称
      companyDepart: '', //部门
      companyPost: '', //岗位
      companyAddress: '', //工作地址
      companyVoucher: '',
      companyVoucherTelphone: '',
      entryDate: '', //入职日期
      dimissionDate: '', //离职日期
      certificate: ''
    }
  ],

  remark: '',
  tenantRelevancys: [] as any,
  tenantAdmin: 0
})
const updateStatus = (status) => {
  formData.value.status = status
  unref(basicsRef)?.setStatus(status)

  console.log(formData.value.status)
}
/** 获得详情 */
const getDetail = async () => {
  const id = params.id as unknown as number
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
      formData.value.userNationalities = formData.value.userNationalities.toString()
      if (isEmpty(formData.value.usersLinkmanSaveReqVOList)) {
        formData.value.usersLinkmanSaveReqVOList = [
          {
            username: '',
            mobile: '',
            relation: ''
          }
        ]
      }
      if (isEmpty(formData.value.usersFamilySaveReqVOList)) {
        formData.value.usersFamilySaveReqVOList = [
          {
            familyName: '',
            familySex: '',
            familyRelation: '',
            familyIdNumber: '',
            workOrganization: '',
            workPost: '',
            address: ''
          }
        ]
      }
      if (isEmpty(formData.value.usersEducationSaveReqVOList)) {
        formData.value.usersEducationSaveReqVOList = [
          {
            schoolName: '',
            schoolAddress: '',
            education: '',
            isFullTime: false,
            profession: '',
            entranceDate: undefined,
            graduateDate: undefined,
            certificate: ''
          }
        ]
      }
      if (isEmpty(formData.value.usersExperienceSaveReqVOList)) {
        formData.value.usersExperienceSaveReqVOList = [
          {
            companyName: '', //单位名称
            companyDepart: '', //部门
            companyPost: '', //岗位
            companyAddress: '', //工作地址
            companyVoucher: '',
            companyVoucherTelphone: '',
            entryDate: '', //入职日期
            dimissionDate: '', //离职日期
            certificate: ''
          }
        ]
      }
    } finally {
      formLoading.value = false
    }
  }
}
/** 提交按钮 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 校验各表单
    await unref(basicsRef)?.validate()
    await unref(postRef)?.validate()
    await unref(residentRef)?.validate()
    await unref(emergencyRef)?.validate()
    await unref(educationRef)?.validate()
    await unref(familyRef)?.validate()
    await unref(workExperienceRef)?.validate()

    // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
    const deepCopyFormData = cloneDeep(unref(formData.value))
    console.log(deepCopyFormData)
    deepCopyFormData.username = deepCopyFormData.mobile
    // 校验都通过后提交表单
    const data = deepCopyFormData as unknown as UserApi.UserVO
    const id = params.id as unknown as number
    if (!id) {
      await UserApi.createUser(data)

      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)

      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'SystemUser' })
}
/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
